﻿/*
The MIT License

Copyright (c) 2009 Gil Beyruth

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

// Shared object variables.
application.roomSO    = null; // a proxied shared object.
application.userList = new Array();
// Start with no swf clients connected.
clientCount = 0;

// Global NetworkConnection to the lobby.
nc = null;

// Short name for this room - for example room_1
roomName = "";

// Timer flag if there is a pending roomList update.
application.pendingUpdate = null;

//LISTA USUARIOS
function listCurrentUsers(){
	trace("-------------- Current Users --------------");
	var i, user;
	var total = application.clients.length;
	trace("There are " + total + " current users.");
	for (i = 0; i < total; i++){
		user = application.clients[i];
		trace(user.getConnectionInfo());
	}
	trace("-------------------------------------------");
}
/**
 * Is this called when this instance changes the proxied shared object?
 **/
function RoomList_onSync(list){
   trace ("roomSO.onSync> Here is what is in the roomList:");
   var names = application.roomSO.getPropertyNames();
   for (var i in names){
	   var propVal = application.roomSO.getProperty(names[i]);
      	trace(" Total users on >" + names[i] +":"+propVal.length); 
	 	for(var j in propVal){
		trace("     roomSO["+names[i]+"].onSync>" + j +" username:"+propVal[j].un +" uid:"+propVal[j].uid);
	 
		}
   } 
}

/**
 * Handler for net connection to the lobby.
 **/
function NetConnection_onStatus(info){
   trace("NetConnection.onStatus> info.code: " + info.code);
   
   if (info.code == "NetConnection.Connect.Success"){
        application.roomSO = SharedObject.get("roomSO", false, nc);
         application.roomSO.onSync = RoomList_onSync;
         trace("onAppStart> roomSO: " + application.roomSO); 
   }
}

/**
 * This function is only called if an attempt to update the room list
 * is made before a connection to the lobby is completed. It is called
 * 1 second after the update failed until it succeeds.
 **/
function updateRoomList(){
   trace("updateRoomList> nc.isConnected: " + nc.isConnected + " roomSO: " + application.roomSO +":"+roomName);
   if (nc.isConnected && application.roomSO && roomName){
	   trace("room update Done!")
       clearInterval(application.pendingUpdate);
	   application.pendingUpdate = null;
       application.roomSO.setProperty(roomName, application.clientList );
   }
}

/** 
 * onAppStart checks that it is an allowed instance by checking its name.
 * It then creates the two shared objects needed by this application:
 *    1. the traceBuffer that allows clients to see application output.
 *    2. the roomsList that keeps track of what rooms have visitors and
 *       and how many they have. Warning: To keep this simple no 
 *       shared object error handling is done! Note: this can be done 
 *       in other ways such as polling the admin.api. 
 **/
application.onAppStart = function(){
   var aName = application.name;
   
   roomName = aName.split("/").pop(); 
   
   trace("onAppStart> application name: " + aName);
   
   // Get the shared object to store client objects (users)
	this.userSO = SharedObject.get("userSO", false);		
	// get the chat SO
	this.chatSO = SharedObject.get("chatSO", false);
   	
	// get the chat SO
	this.roomSO = SharedObject.get("roomSO", false);
	this.roomSO.onSync = RoomList_onSync;
   	trace("onAppStart> roomSO: " + this.roomSO); 
  // get the chat SO
	this.gameSO = SharedObject.get("gameSO", false);
		
	// hash of connected users
	this.clientList = [];
	// first user gets the uid 1
	this.uid = 1;
   
   //USUARIO TIME
	Client.prototype.getTimeConnected = function() {
		var now = new Date().getTime();
		return (now - this.connectTime)/1000; // seconds
	}
	//USUARIO PING
	Client.prototype.getPingTime = function(){
		if (this.ping()){
			if(this > 20000)application.disconnect(this, {msg : "Low bandwidth. Ping to high. Disconnected."});
			return this.getStats().ping_rtt / 2;
		}
		else{
			application.disconnect(this, {msg : "Low bandwidth. Ping to high. Disconnected."});
			return "Cliente não conectado."
		}
		
	}
	
	//USUARIO CONNECTION
	Client.prototype.getConnectionInfo = function() {
		if(this.username==undefined)this.username="SERVER";
		if(this.uid==undefined)this.uid="0";
	  		return 	"  IP: "              	+ this.ip +
					", user name: "       	+ this.username +
					", uid: "      			+ this.uid +
					", id: "      			+ this.id +
					", connection time: " 	+ this.getTimeConnected() +
					", ping time: "       	+ this.getPingTime();
	}
	//USUARIO NAME
	Client.prototype.getUserName = function(){
		return client.username;
	}
	
	Client.prototype.checkBandwidth = function() 
	{
		application.calculateClientBw(this);
	}
	
	
   nc = new NetConnection();
   nc.onStatus = NetConnection_onStatus;
   var result = nc.connect( 'rtmp://localhost/lobby_rooms/lobby', roomName,"SERVER",000);
   trace("onAppStart> nc: " + nc + " connect result: " + result);
   
   	
	setInterval(listCurrentUsers, 60000);

}


application.calculateClientBw = function(client)
{
	var res = new Object();
	res.latency = 0;
	res.cumLatency = 1;
	res.bwTime = 0;
	res.count = 0;
	res.sent = 0;
	res.client = client;
	var stats = client.getStats();
	var now = (new Date()).getTime()/1;
	res.pakSent = new Array();
	res.pakRecv = new Array();
	res.beginningValues = {b_down:stats.bytes_out, b_up:stats.bytes_in, time:now};
	res.onResult = function(p_val) {

		var now = (new Date()).getTime()/1;
		this.pakRecv[this.count] = now;
		trace("** onResult this.count = " + this.count + " : this.sent " + this.sent);
		//trace( "Packet interval = " + (this.pakRecv[this.count] - this.pakSent[this.count])*1  );
		this.count++;
		var timePassed = (now - this.beginningValues.time);

		if (this.count == 1) {
			this.latency = Math.min(timePassed, 800);
			this.latency = Math.max(this.latency, 10);
		}


		//trace("count = " + this.count + ", sent = " + this.sent + ", timePassed = " + timePassed);

		// If we have a hi-speed network with low latency send more to determine
		// better bandwidth numbers, send no more than 6 packets
		if ( this.count == 2 && (timePassed<2000))
		{
			this.pakSent[res.sent++] = now;
			this.cumLatency++;
			this.client.call("onBWCheck", res, application.payload);
		}
		else if ( this.sent == this.count )
		{	
			// See if we need to normalize latency
			if ( this.latency >= 100 )
			{ // make sure we detect sattelite and modem correctly
				if (  this.pakRecv[1] - this.pakRecv[0] > 1000 )
				{
					this.latency = 100;
				}
			}

			// Got back responses for all the packets compute the bandwidth.
			var stats = this.client.getStats();
			var deltaDown = (stats.bytes_out - this.beginningValues.b_down)*8/1000;
			var deltaTime = ((now - this.beginningValues.time) - (this.latency * this.cumLatency) )/1000;
			if ( deltaTime <= 0 )
				deltaTime = (now - this.beginningValues.time)/1000;
			
			var kbitDown = Math.round(deltaDown/deltaTime);

			trace("onBWDone: kbitDown = " + kbitDown + ", deltaDown= " + deltaDown + ", deltaTime = " + deltaTime + ", latency = " + this.latency + "KBytes " + (stats.bytes_out - this.beginningValues.b_down)/1024) ;

			this.client.call("onBWDone", null, kbitDown,  deltaDown, deltaTime, this.latency );
		}
	}
	res.pakSent[res.sent++] = now;
	client.call("onBWCheck", res, "");
	res.pakSent[res.sent++] = now;
	client.call("onBWCheck", res, application.payload);

}


application.onConnect = function(client, room, userName,  password , userStatus){
 	
	client.connectTime = new Date().getTime();
	trace("onConnect> client: " + client + " room: " + room + " application.name: " + application.name);
	//client.writeAccess = "/../../../"; // no write permissions.
	application.acceptConnection(client);
   
	
	this.clientCount++; 
	client.uid = this.uid;
	client.username = userName;
	client.userStatus = userStatus;
	client.room = room;
	this.clientList.push({un:userName,r:room,uid: this.uid,us:userStatus});
	trace("CLIENT LIST USERNAME: "+this.clientList[0].un)	
	this.userSO.setProperty(client.uid, client);
	
	var msg = "<font color='#666666'><b>*** " + client.username + " joined ***</b></font><br>";
	this.chatSO.send("onMsgSend", msg);
	
	// inform the client of its uid. (invokes _nc.onUserid on the client)
	// This kicks the clientside app into life.
	client.call("onUserid", null, client.uid);
	trace("CALL FUNCTION callFromServer :"+ client.uid)
	
	// increase uid ready for next user
	this.uid++;
				
		
	if (nc.isConnected && this.roomSO && roomName){
	   this.roomSO.setProperty(roomName, this.clientList );
	}
	else{
	  if (! application.pendingUpdate){
		  trace("setInterval !!"+application.pendingUpdate)
		 application.pendingUpdate = setInterval(updateRoomList, 1000);
	  }
	}
	trace("A client has connected. There are now: " + clientCount + " client(s).");
}

application.onDisconnect = function(client){
	for(var i in this.clientList){
			trace(i+":"+this.clientList[i])
	}
	if(this.clientList[0]){
		 
		 for(var i=0;i< this.clientList.length;i++){
			 if(this.clientList[i])trace("Users on the room: " +this.clientList[i].un)
			
			if(this.clientList[i].uid==client.uid){
				trace("removed user:" +this.clientList[i].un);
				userRemoved = this.clientList.splice(i,i+1);
				trace("removed user:" +userRemoved[0].un);
				
			}
			if(this.clientList[i])trace("Users on the room : " +this.clientList[i].un)
		}
		this.clientList.sort();
		for(var i in this.clientList){
			trace(i+":"+this.clientList[i])
		}
	 }else{
		trace("empty clientList") 
	}
	 this.clientCount--;
	trace("Client disconnected. UID:  " +client.uid);
	
	var msg = "<font color='#666666'><b>*** " + client.username + " has left ***</b></font><br>";
	this.chatSO.send("onMsgSend", msg);
	this.userSO.setProperty(client.uid, null);
	if (nc.isConnected && this.roomSO && roomName){
     this.roomSO.setProperty(roomName, this.clientList );
   }
   else
   {
      if (!application.pendingUpdate){
          trace("setInterval !!"+application.pendingUpdate)
		application.pendingUpdate = setInterval(updateRoomList, 1000);
      }
   }
   trace("A client has disconnected. There are now: " + clientCount + " client(s).");
}

application.onAppStop = function(){
	this.clientList = undefined;
   if (this.roomSO){
         this.roomSO.setProperty(roomName, null );
   }
}


/*
* Client.prototype.getPageUrl
* 				Public API to return URL of the HTML page.				
* 
*/

Client.prototype.getPageUrl = function() {
	return this.pageUrl;
}

/*
* Client.prototype.getReferrer
* 				Public API to return Domain URL of the client SWF file.				
* 
*/
Client.prototype.getReferrer = function() {
	return this.referrer;
}


/**
* String.prototype.trim:
* 			Function to trim spaces in start an end of an input string.
* returns:
* 		a trimmed string without any leading & ending spaces.
* 		 
*/
String.prototype.trim = function () {
	
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

